package com.palfund.autoshowviewpager;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

//备注:注意ViewPager和RadioGroup监听器的相互调用
public class MainActivity extends AppCompatActivity {
    private static boolean runned = true;
    private boolean pasued = false;
    private static int curIndex = 1;
    private ViewPager mViewPager;
    private int[] mIconIds;
    private AutoThread mThread;
    long downTime = 0;
    float downX = 0;
    float downY = 0;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        runned = true;
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        mIconIds = new int[]{R.drawable.bg04, R.drawable.bg03, R.drawable.bg02, R.drawable.bg05};
        AutoShowPagerAdapter adapter = new AutoShowPagerAdapter(this, mIconIds);
        mViewPager.setAdapter(adapter);
        // 设置viewpager每个页面之间的间距
        mViewPager.setPageMargin(30);
        //初始化dots
        initDots(radioGroup, mIconIds);
        //非自动轮播设置默认显示
        //mViewPager.setCurrentItem(1, false);
        //((RadioButton) radioGroup.getChildAt(0)).setChecked(true);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int
                    positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                Log.i("MainActivity", "---onPageSelected()--->" + position);
                if (position == 0) {
                    // 废弃((RadioButton) radioGroup.getChildAt(mIconIds.length - 1)).setChecked
                    // (true);让onPageScrollStateChanged处理
                } else if (position == mIconIds.length + 1) {
                    // 废弃((RadioButton) radioGroup.getChildAt(0)).setChecked(true);
                    // 让onPageScrollStateChanged处理
                } else {
                    ((RadioButton) radioGroup.getChildAt(position - 1)).setChecked(true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.i("MainActivity", "---onPageScrollStateChanged()--->" + state);
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    int currentItem = mViewPager.getCurrentItem();
                    Log.i("MainActivity", "---onPageScrollStateChanged()--->currentItem" +
                            currentItem);
                    if (currentItem == 0) {
                        Log.i("MainActivity", "---onPageScrollStateChanged()--->Zero");
                        mViewPager.setCurrentItem(mIconIds.length, false);
                    }
                    if (currentItem == mIconIds.length + 1) {
                        Log.i("MainActivity", "---onPageScrollStateChanged()--->Max");
                        mViewPager.setCurrentItem(1, false);
                    }
                }

            }
        });
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int id) {
                for (int i = 0; i < mIconIds.length; i++) {
                    if (radioGroup.getChildAt(i).getId() == id) {
                        mViewPager.setCurrentItem(i + 1, false);
                        curIndex = i + 1;
                    }
                }
            }
        });
        mThread = new AutoThread();

        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downTime = System.currentTimeMillis();
                        downX = motionEvent.getX();
                        downY = motionEvent.getY();
                        mThread.pauseing();
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        mThread.starting();
                        break;
                    case MotionEvent.ACTION_UP:
                        long upTime = System.currentTimeMillis();
                        float upX = motionEvent.getX();
                        float upY = motionEvent.getY();
                        // 实现点击跳转
                        if (upTime - downTime< 200 && Math.abs(upX - downX) < 30 && Math
                                .abs(upY - downY) < 30) {
                            Toast.makeText(MainActivity.this, String.valueOf(mViewPager
                                    .getCurrentItem()), Toast.LENGTH_SHORT).show();
                            // 跳转后暂停
                            mThread.pauseing();
                        } else {
                            mThread.starting();
                        }
                        break;
                }
                return false;
            }
        });
        mThread.start();
    }

    private void initDots(RadioGroup radioGroup, int[] iconIds) {
        int per = getResources().getDisplayMetrics().widthPixels / 2 / iconIds.length;
        for (int i = 0; i < iconIds.length; i++) {
            RadioButton radioButton = new RadioButton(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(per, ViewGroup
                    .LayoutParams.MATCH_PARENT);
            radioButton.setLayoutParams(layoutParams);
            radioButton.setGravity(Gravity.CENTER);
            radioButton.setButtonDrawable(R.drawable.dot_selector);
            radioButton.setBackgroundResource(android.R.color.transparent);
            radioGroup.addView(radioButton);
        }
    }

    class AutoThread extends Thread {
        private void pauseing() {
            pasued = true;
        }

        private void starting() {
            pasued = false;
            synchronized (AutoThread.class) {
                AutoThread.class.notify();
            }
        }

        @Override
        public void run() {
            curIndex = 0;
            while (runned) {
                Log.i("AutoThread", curIndex + "---run()--->" + System.currentTimeMillis());
                Log.i("AutoThread", curIndex + "---run()--->" + Thread.currentThread().getName());
                curIndex++;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mViewPager.setCurrentItem(curIndex);
                    }
                });
                SystemClock.sleep(1000);
                if (pasued) {
                    synchronized (AutoThread.class) {
                        try {
                            AutoThread.class.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        // 再次开始轮播
        mThread.starting();
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 暂停轮播
        mThread.pauseing();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止轮播
        runned = false;
    }
}
